<template>
  <div class="order-page">
    <!-- 头部 -->
    <div class="header">
      <div class="back" @click="$router.back()">
        <i class="iconfont icon-back"></i>
      </div>
      <div class="title">确认订单</div>
    </div>

    <!-- 送货地址 -->
    <div class="address-section" @click="goToDeliveryAddress">
      <template v-if="selectedAddress">
        <div class="address-info">
          <div class="contact">
            <span class="name">{{ selectedAddress.contactName }}</span>
            <span class="sex">{{ selectedAddress.contactSex === 1 ? '先生' : '女士' }}</span>
            <span class="tel">{{ selectedAddress.contactTel }}</span>
          </div>
          <div class="address">{{ selectedAddress.address }}</div>
        </div>
      </template>
      <div class="no-address" v-else>
        <span>请选择送货地址</span>
      </div>
      <i class="iconfont icon-right"></i>
    </div>

    <!-- 商家信息 -->
    <div class="business-section" v-if="businessInfo">
      <div class="business-info">
        <img :src="businessInfo.businessImg" :alt="businessInfo.businessName">
        <span>{{ businessInfo.businessName }}</span>
      </div>
    </div>

    <!-- 订单明细 -->
    <div class="order-detail">
      <div class="food-list">
        <div class="food-item" v-for="item in cartItems" :key="item.foodId">
          <div class="food-name">{{ item.food?.foodName }}</div>
          <div class="food-amount">
            <span>x{{ item.quantity }}</span>
            <span class="price">￥{{ item.food?.foodPrice * item.quantity }}</span>
          </div>
        </div>
      </div>
      <div class="delivery-fee">
        <span>配送费</span>
        <span>￥{{ businessInfo?.deliveryPrice || 0 }}</span>
      </div>
      <div class="total">
        <span>合计</span>
        <span class="total-price">￥{{ totalPrice }}</span>
      </div>
    </div>

    <!-- 提交订单按钮 -->
    <div class="submit-btn" :class="{ disabled: !selectedAddress }" @click="submitOrder">
      提交订单
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { useCartStore } from '../../stores/cart'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()
const businessInfo = ref(null)
const cartItems = ref([])
const selectedAddress = ref(null)
const userId = localStorage.getItem('userId')

// 获取商家信息
const getBusinessInfo = async () => {
  try {
    const res = await axios.get('/business/getBusinessById', {
      params: { businessId: route.query.businessId }
    })
    businessInfo.value = res.data
  } catch (error) {
    console.error('获取商家信息失败:', error)
  }
}

// 获取购物车信息
const getCartInfo = async () => {
  try {
    const res = await axios.get('/cart/listCart', {
      params: {
        userId,
        businessId: route.query.businessId
      }
    })
    cartItems.value = res.data
  } catch (error) {
    console.error('获取购物车信息失败:', error)
  }
}

// 获取地址信息
const getAddressInfo = async () => {
  if (!route.query.daId) return
  try {
    const res = await axios.get('/deliveryAddress/getDeliveryAddressById', {
      params: { daId: route.query.daId }
    })
    selectedAddress.value = res.data
  } catch (error) {
    console.error('获取地址信息失败:', error)
  }
}

// 跳转到地址选择页面
const goToDeliveryAddress = () => {
  router.push({
    path: '/deliveryAddress',
    query: {
      from: 'order',
      businessId: route.query.businessId
    }
  })
}

// 计算总价
const totalPrice = computed(() => {
  const foodTotal = cartItems.value.reduce((total, item) => {
    return total + (item.food?.foodPrice || 0) * item.quantity
  }, 0)
  return foodTotal + (businessInfo.value?.deliveryPrice || 0)
})

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    alert('请选择送货地址')
    return
  }

  try {
    const res = await axios.post('/orders/createOrders', null, {
      params: {
        userId,
        businessId: route.query.businessId,
        daId: selectedAddress.value.daId,
        orderTotal: totalPrice.value
      }
    })
    // 清空购物车
    await cartStore.clearCart()
    // 跳转到支付页面
    router.push({
      path: '/payment',
      query: { orderId: res.data }
    })
  } catch (error) {
    console.error('创建订单失败:', error)
    alert('创建订单失败，请重试')
  }
}

onMounted(() => {
  if (!userId) {
    router.push('/login')
    return
  }
  getBusinessInfo()
  getCartInfo()
  getAddressInfo()
})
</script>

<style scoped>
.order-page {
  padding-top: 44px;
  padding-bottom: 60px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 100;
}

.back {
  padding: 10px;
  margin-left: -10px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
}

.address-section {
  background: #fff;
  margin-top: 10px;
  padding: 15px;
  display: flex;
  align-items: center;
}

.address-info {
  flex: 1;
}

.contact {
  margin-bottom: 5px;
}

.contact .name {
  font-size: 16px;
  margin-right: 10px;
}

.contact .sex {
  color: #666;
  margin-right: 10px;
}

.contact .tel {
  color: #666;
}

.address {
  font-size: 14px;
  color: #666;
}

.no-address {
  flex: 1;
  color: #666;
}

.business-section {
  background: #fff;
  margin-top: 10px;
  padding: 15px;
}

.business-info {
  display: flex;
  align-items: center;
}

.business-info img {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.order-detail {
  background: #fff;
  margin-top: 10px;
  padding: 15px;
}

.food-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.food-name {
  color: #333;
}

.food-amount {
  color: #666;
}

.food-amount .price {
  margin-left: 10px;
  color: #ff6b01;
}

.delivery-fee {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.total {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.total-price {
  color: #ff6b01;
  font-size: 18px;
  font-weight: bold;
}

.submit-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.submit-btn.disabled {
  background: #ccc;
}
</style>